<template>
  <xyEnergyhead>
    <EnergyHead
      title="加热时长统计"
      icon="dashboard-1"
      :info="info"
      @download-chart="downloadChart"
      @init-chart="initChart"
    ></EnergyHead>
    <div class="chart-card">
      <div class="stat-card">
        <div class="stat-label">今日加热</div>
        <div class="stat-value">4.2 h</div>
        <div class="trend-down">
          <span><i class="el-icon-bottom"></i> 0.5%</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">本月加热</div>
        <div class="stat-value">98.5 h</div>
        <div class="trend-up">
          <span><i class="el-icon-top"></i> 12.3%</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">本年加热</div>
        <div class="stat-value">1,150 h</div>
        <div class="trend-up">
          <span><i class="el-icon-top"></i> 8.7%</span>
        </div>
      </div>
    </div>
    <div v-if="typeShow" class="chart-container">
      <div ref="heatingChart" class="chart-wrapper"></div>
    </div>
    <div v-if="!typeShow" class="table-view">
      <el-table
        :data="tableData"
        style="width: 100%"
        size="large"
        :header-cell-style="{ background: '#0066ff0d', color: '#0066ff' }"
      >
        <el-table-column prop="date" label="月份"> </el-table-column>
        <el-table-column prop="name" label="用电量(kWh)"> </el-table-column>
        <el-table-column prop="address" label="同比变化">
          <template slot-scope="scope">
            <span :class="scope.row.address === '4.5%' ? 'trend-up' : 'trend-down'"
              ><i
                :class="scope.row.address === '4.5%' ? 'el-icon-top' : 'el-icon-bottom'"
              ></i
              >{{ scope.row.address }}</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详细统计信息 -->
    <el-card class="main-analysis">
      <div class="main-analysis-header">
        <svg-icon icon-class="dashboard-1"></svg-icon>
        <span class="main-analysis-title">加热时长详细分析</span>
      </div>
      <div class="main-analysis-content">
        <div class="main-analysis-content-item">
          <div>今日最长连续加热</div>
          <div class="main-analysis-content-item-value">1.5 h (09:00-10:30)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>今日最短加热时段</div>
          <div class="main-analysis-content-item-value">15 min (16:00-16:15)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>今日平均加热功率</div>
          <div class="main-analysis-content-item-value">85.7% 满负荷</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最长连续加热</div>
          <div class="main-analysis-content-item-value">1.3 h (09:30-10:30)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最短加热时段</div>
          <div class="main-analysis-content-item-value">10 min (15:45-15:55)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日平均加热功率</div>
          <div class="main-analysis-content-item-value">82.3% 满负荷</div>
        </div>
      </div>
    </el-card>
  </xyEnergyhead>
</template>

<script>
import xyEnergyhead from "../../components/xy-energy-head.vue";
import EnergyHead from "./EnergyHead.vue";
import * as echarts from "echarts";

export default {
  components: { xyEnergyhead, EnergyHead },
  props: {
    typeShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      heatingChart: null,
      currentTimeDimension: "day", // 默认显示日维度数据
      chartData: {
        day: {
          labels: Array.from({ length: 24 }, (_, i) => `${i}:00`),
          data: Array.from({ length: 24 }, (_, i) => {
            // 模拟一天内的加热时长，早晚温差大时加热时间长
            if ((i >= 5 && i <= 9) || (i >= 16 && i <= 22)) {
              return 0.8 + Math.random() * 0.4;
            } else if (i >= 22 || i <= 5) {
              return 1.0 + Math.random() * 0.3;
            } else {
              return 0.2 + Math.random() * 0.3;
            }
          }),
        },
        month: {
          labels: ["第1周", "第2周", "第3周", "第4周"],
          data: [38.5, 36.2, 34.8, 33.5],
        },
        year: {
          labels: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          data: [150, 140, 120, 80, 50, 30, 25, 20, 40, 70, 110, 135],
        },
      },
      tableData: [
        {
          date: "1月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "2月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "3月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "4月",
          name: "650 KWh",
          address: "2.3%",
        },
      ],
      info: {
        title: "加热时长统计详情",
        listInfo: [
          {
            title: "此图表展示了加热设备运行时间的统计信息。",
          },
          {
            title: "加热时长与季节、气温变化密切相关，冬季通常会有更长的加热时间。",
          },
          {
            title: "通过分析加热时长数据，可以优化设备运行策略，提高能源利用效率。",
          },
        ],
      },
    };
  },
  mounted() {
    if (this.typeShow) {
      this.$nextTick(() => {
        this.initHeatingChart();
      });
    }
    this.updateTableData();
  },
  beforeDestroy() {
    if (this.heatingChart) {
      this.heatingChart.dispose();
    }
  },
  watch: {
    typeShow: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initHeatingChart();
          });
        } else {
          if (this.heatingChart) {
            this.heatingChart.dispose();
            this.heatingChart = null;
          }
          this.updateTableData();
        }
      },
      immediate: true,
    },
    currentTimeDimension: {
      handler() {
        if (this.typeShow) {
          this.$nextTick(() => {
            this.initHeatingChart();
          });
        } else {
          this.updateTableData();
        }
      },
    },
  },
  methods: {
    initChart() {
      if (this.typeShow) {
        this.initHeatingChart();
      } else {
        this.updateTableData();
      }
    },
    switchTimeDimension(dimension) {
      this.currentTimeDimension = dimension;
    },

    updateTableData() {
      // 表格数据更新逻辑
    },

    initHeatingChart() {
      if (!this.$refs.heatingChart) return;

      if (this.heatingChart) {
        this.heatingChart.dispose();
      }

      this.heatingChart = echarts.init(this.$refs.heatingChart);

      const currentData = this.chartData[this.currentTimeDimension];

      // 使用 ECharts 的 LinearGradient 创建渐变色
      const gradient = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(255, 51, 102, 0.8)" },
        { offset: 1, color: "rgba(255, 51, 102, 0.2)" },
      ]);

      const option = {
        title: {
          text: this.getTimeDimensionTitle(),
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            let result = params[0].name + "<br/>";
            params.forEach((param) => {
              result += `<div style="display:flex;align-items:center;">
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>
            ${param.seriesName}: ${param.value}h
          </div>`;
            });
            return result;
          },
        },
        xAxis: {
          type: "category",
          data: currentData.labels,
          axisLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#64748b",
            rotate: this.currentTimeDimension === "day" ? 0 : 45,
          },
          boundaryGap: true,
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisLabel: {
            color: "#64748b",
            formatter: (value) => {
              return value + "h";
            },
          },
          name: this.getYAxisName(),
          nameTextStyle: {
            color: "#64748b",
            fontSize: 13,
            fontWeight: "bold",
          },
        },
        series: [
          {
            name: this.getSeriesName(),
            type: "line", // 改为折线图
            data: currentData.data,
            smooth: true,
            symbolSize: 8,
            itemStyle: {
              color: "#ff3366", // 使用纯色而不是渐变色
            },
            lineStyle: {
              width: 3,
              color: "#ff3366",
            },
            areaStyle: {
              color: gradient, // 保留区域填充效果
            },
            emphasis: {
              focus: "series",
              itemStyle: {
                borderColor: "#fff",
                borderWidth: 2,
                shadowColor: "rgba(0, 0, 0, 0.3)",
                shadowBlur: 5,
              },
            },
          },
        ],
        grid: {
          left: "5%",
          right: "5%",
          bottom: "15%",
          top: "20%",
          containLabel: true,
        },
        color: ["#ff3366"],
      };

      this.heatingChart.setOption(option);
      window.addEventListener("resize", this.handleResize);
    },

    getTimeDimensionTitle() {
      const titles = {
        day: "24小时加热时长统计",
        month: "月加热时长统计",
        year: "年度加热时长统计",
      };
      return titles[this.currentTimeDimension];
    },

    getYAxisName() {
      return "加热时长 (小时)";
    },

    getSeriesName() {
      const names = {
        day: "小时加热时长",
        month: "周加热时长",
        year: "月加热时长",
      };
      return names[this.currentTimeDimension];
    },

    handleResize() {
      if (this.heatingChart) {
        this.heatingChart.resize();
      }
    },
    downloadChart() {
      if (!this.heatingChart) {
        console.error("图表实例不存在");
        return;
      }

      try {
        // 使用 ECharts 的 getDataURL 方法获取图片数据
        const dataURL = this.heatingChart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.download = `电费统计图表_${new Date().getTime()}.png`;
        link.href = dataURL;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error("下载图表失败:", error);
        // 如果需要，可以显示错误消息
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./EnergyAnalysis.scss";

.chart-container {
  padding: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.chart-card {
  display: flex;
  justify-content: space-between;
  gap: 20px;

  .stat-card {
    flex: 1;
    margin: 15px 0;
    position: relative;
    background: linear-gradient(
      135deg,
      rgba(0, 102, 255, 0.05) 0%,
      rgba(255, 51, 102, 0.05) 100%
    );
    border-radius: 12px;
    padding: 18px;
    transition: all 0.3s;
    border: 1px solid rgba(0, 102, 255, 0.1);
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  }

  .stat-card::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 4px;
    width: 100%;
    background: linear-gradient(90deg, #0066ff, #ff3366);
  }

  .stat-label {
    font-size: 0.9rem;
    color: #64748b;
    font-weight: 500;
    text-align: center;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #0055ff;
    margin: 10px 0;
    text-align: center;
  }
}

.trend-up {
  color: #10b981;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.trend-down {
  color: #ef4444;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.table-view {
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
}

.main-analysis {
  margin-top: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.main-analysis-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #0055ff;
  margin-bottom: 20px;

  .svg-icon {
    margin-right: 10px;
    font-size: 1.3rem;
    width: 1.3rem;
    height: 1.3rem;
  }
}

.main-analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.main-analysis-content-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;

  div:first-child {
    font-size: 0.9rem;
    color: #64748b;
    margin-bottom: 8px;
  }

  .main-analysis-content-item-value {
    font-size: 1.1rem;
    font-weight: 600;
    color: #0055ff;
  }
}

@media (max-width: 768px) {
  .chart-card {
    flex-direction: column;

    .stat-card {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .main-analysis-content {
    grid-template-columns: 1fr;
  }

  .chart-wrapper {
    height: 300px;
  }
}
</style>
